﻿//-----------------------------------------------------------------------
// <copyright file="TenancyRepository.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.Infrastructure.Mocks.Repositories{    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using AbstractSaaSTemplate.Domain.Exceptions;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Infrastructure.Mocks.Repositories.Core;

    /// <summary>
    /// Implements 'ITenancyRepository' and all its contract, providing
    /// data accessibility to the aggregate 'Tenancy'.
    /// </summary>
    public sealed class TenancyRepository : ITenancyRepository
    {
        /// <summary>
        /// Initializes a new instance of the TenancyRepository class
        /// injecting dependencies to generic repositories.
        /// </summary>
        /// <param name="repositoryForMemberships">The repository to operate 'Memberships'.</param>
        public TenancyRepository(
            IMembershipRepository repositoryForMemberships)
        {
            this.RepositoryForMemberships = repositoryForMemberships;

#if DEBUG
            // DEFAULT DATA LOADING RELATED TO 'CUSTOMISATION'.
            if (TenantsTable.Count < 2)
            {
                TenantsTable.Add(new Tenant()
                {
                    Id = 1,
                    Key = "tenant-alpha",
                    CompanyName = "Tenant Alpha Ltda.",
                    DisplayName = "Alpha",
                    Culture = CultureInfo.GetCultureInfo("pt-BR"),
                    InstanceSetup = new Domain.Models.ValueObjects.InstanceInfo()
                    {
                        LayoutName = "Default",
                        ThemeName = "Default"
                    }
                });

                TenantsTable.Add(new Tenant()
                {
                    Id = 2,
                    Key = "tenant-beta",
                    CompanyName = "Tenant Beta Ltda.",
                    DisplayName = "Beta",
                    Culture = CultureInfo.GetCultureInfo("en-US"),
                    InstanceSetup = new Domain.Models.ValueObjects.InstanceInfo()
                    {
                        LayoutName = "Default",
                        ThemeName = "Default"
                    }
                });
            }
#endif
        }

        /// <summary>
        /// Gets the repository to operate 'Memberships'.
        /// </summary>
        public IMembershipRepository RepositoryForMemberships { get; private set; }

        /// <summary>
        /// Gets a list of all entries of 'Tenant' available in the system.
        /// </summary>
        public IEnumerable<Tenant> Tenants
        {
            get
            {
                return TenantsTable.ToArray();
            }
        }

        /// <summary>
        /// Gets the table of 'Tenant'
        /// </summary>
        private static IList<Tenant> TenantsTable
        {
            get
            {
                return InMemoryRepositoryHelper.GetTable<Tenant>();
            }
        }

        /// <summary>
        /// Creates or updates a 'Tenant' in the system.
        /// </summary>
        /// <param name="entity">The entry of 'Tenant' which will be either created or updated.</param>
        public void AddOrUpdateTenant(Tenant entity)
        {
            // validates the method input against null reference.
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            // seeks for the entry in the data source.
            // if existing, we shall update it instead
            // of creating a new one.
            var tenant = TenantsTable
                .Where(d => d.Id == entity.Id)
                .FirstOrDefault();

            // checks unicity of the key for new entries
            // if the tenant was not found by id, it can't have the same
            // key as another existing person
            var uniquePropety = entity.GetType().GetProperty("Key");
            if (tenant == null && this.Tenants.Any(d => d.Key == entity.Key))
            {
                throw new AttemptToPersistEntityWithDuplicatedUniqueKeyException(uniquePropety);
            }

            // now if we are updating a tenant and we try to use a key
            // that is already taken by another, it's also wrong
            if (tenant != null)
            {
                var tenantWhoOwnsKey = this.Tenants
                    .Where(d => d.Key == entity.Key)
                    .FirstOrDefault();

                if (tenantWhoOwnsKey.Id != tenantWhoOwnsKey.Id)
                {
                    throw new AttemptToPersistEntityWithDuplicatedUniqueKeyException(uniquePropety);
                }
            }

            // if none, creates a new one.
            if (tenant == null)
            {
                tenant = new Tenant();
                TenantsTable.Add(tenant);

                // because it is an in-memory implementation
                // we generate the id based on the last entry
                var lastId = default(long);
                if (TenantsTable.Count != 0)
                {
                    lastId = TenantsTable.Max(d => d.Id);
                }

                tenant.Id = lastId + 1;

                // now we set the other readonly items
                tenant.Key = entity.Key;
            }

            // we save the data to the data source.
            InMemoryRepositoryHelper.CopyDataAcrossEntity<Tenant>(entity, tenant);

            // we retrieve the id of the returning
            // entity, based on what it was generated
            // in the data source.
            entity.Id = tenant.Id;
        }

        /// <summary>
        /// Retrieves a tenant by its Id.
        /// </summary>
        /// <param name="id">The if of the tenant.</param>
        /// <returns>If a tenant matches the Id, returns it; otherwise, returns null.</returns>
        public Tenant GetTenantById(long id)
        {
            var tenant = TenantsTable
                .Where(d => d.Id == id)
                .FirstOrDefault();

            if (tenant == null)
            {
                return tenant;
            }

            // retrieves a tenant.
            return tenant;
        }

        /// <summary>
        /// Retrieves a tenant by its key.
        /// </summary>
        /// <param name="key">The key of the tenant.</param>
        /// <returns>If a tenant matches the key, returns it; otherwise, returns null.</returns>
        public Tenant GetTenantByKey(string key)
        {
            var tenant = TenantsTable
                .Where(d => string.Compare(d.Key, key, StringComparison.OrdinalIgnoreCase) == 0)
                .FirstOrDefault();

            if (tenant == null)
            {
                return tenant;
            }

            // retrieves a tenant.
            return tenant;
        }
    }
}


